<template>
  <div class="add-native-anchor">
    <div class="native-anchor-content">
      <div class="native-anchor-item">
        <div class="promotion">
          <span class="title">推广内容</span>
          <el-radio-group v-model="boNetServiceType" @change="handleRadioNetServiceType">
            <!-- <el-radio-button label="常规应用下载" value="GENERAL" /> -->
            <el-radio-button label="跳转微信" value="2" />
            <!-- <el-radio-button label="快应用" value="QUICK_APP" /> -->
          </el-radio-group>
        </div>
        <div class="basic-settings">
          <span class="title">基本设置</span>
          <div class="basic-settings-form">
            <el-form :model="form" label-width="auto" label-position="top">
              <el-form-item label="工具名称">
                <el-input v-model="form.anchorInfo.toolTitle" maxlength="15" show-word-limit placeholder="请输入工具名称" />
              </el-form-item>

              <!-- <template v-if="boNetServiceType === 'GENERAL'">
                <el-form-item label="APP下载配置">
                  <el-checkbox-group v-model="checkedCities" :min="1">
                    <el-checkbox-button v-for="city in cities" :key="city" :label="city" :value="city">
                      {{ city }}
                    </el-checkbox-button>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="iOS下载配置">
                  <el-input v-model="form.name" show-word-limit placeholder="请输入iOS appstore下载链接">
                    <template #prepend>iOS下载链接</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="APP调起链接">
                  <el-input v-model="form.name" show-word-limit placeholder="请输入APP调起链接">
                    <template #prepend>APP调起链接</template>
                  </el-input>
                </el-form-item>
              </template> -->

              <template v-if="boNetServiceType == '2'">
                <el-form-item label="跳转场景">
                  <el-checkbox-group v-model="smNetServiceType">
                    <el-checkbox-button v-for="itm in smNetServiceTypeList" :key="itm.value" :label="itm.value">
                      {{ itm.label }}
                    </el-checkbox-button>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="巨量引擎广告主ID">
                  <el-input v-model="form.advertiserId" show-word-limit placeholder="请输入巨量引擎广告主ID" />
                </el-form-item>
                <el-form-item label="微信小程序资产id">
                  <!-- <el-input v-model="form.anchorInfo.netServiceAnchor.instanceId" show-word-limit placeholder="请输入微信小程序ID" type="number" /> -->
                  <el-select v-model="form.anchorInfo.netServiceAnchor.instanceId" @change="handelInstanceId">
                    <el-option v-for="(item, index) in appList" :key="index" :label="item.name" :value="item.instanceId"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="小程序路径参数">
                  <el-input v-model="form.anchorInfo.netServiceAnchor.pathParam" disabled show-word-limit placeholder="请输入小程序路径参数" />
                </el-form-item>
              </template>
            </el-form>
          </div>
        </div>
        <div class="inlet-settings">
          <span class="title">锚点入口配置</span>
          <div class="basic-settings-form">
            <el-form :model="form" label-width="auto" label-position="top">
              <el-form-item label="IOS端锚点标题">
                <el-input
                  v-model="form.anchorInfo.netServiceAnchor.iosAnchorTitle"
                  show-word-limit
                  maxlength="12"
                  placeholder="请输入与IOS端应用名称相关的引导文案"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="安卓端锚点标题">
                <el-input
                  v-model="form.anchorInfo.netServiceAnchor.androidAnchorTitle"
                  show-word-limit
                  maxlength="12"
                  placeholder="请输入与安卓端应用名称相关的引导文案"
                >
                </el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="page-settings">
          <span class="title">锚点页面配置</span>
          <div class="basic-settings-form">
            <el-form :model="form" label-width="auto" label-position="top">
              <el-form-item label="顶部头图">
                <!-- <NewImageUpload v-model="headImageList" :accountId="appStore.accountId" :advertiserId="form.advertiserId" :enableCrop="true" /> -->
                <CropperImageUpload
                  v-model="headImageList"
                  :accountId="appStore.accountId"
                  :advertiserId="form.advertiserId"
                  :limit="5"
                  accept="image/jpeg,image/png"
                  tip="请上传大小不超过5M的图片，支持裁剪，推荐尺寸2:1"
                  dialog-title="请裁剪您的图片"
                  :auto-crop-width="240"
                  :auto-crop-height="120"
                  :fixed="true"
                  :center-box="true"
                  :fixed-number="[2, 1]"
                  :fixed-box="false"
                  @crop-success="handleImageList"
                />
              </el-form-item>
              <el-form-item label="应用icon" class="app-icon">
                <!-- <NewImageUpload v-model="iconImages" :accountId="appStore.accountId" :advertiserId="form.advertiserId" limit="1" :enableCrop="true" /> -->
                <CropperImageUpload
                  v-model="iconImages"
                  :accountId="appStore.accountId"
                  :advertiserId="form.advertiserId"
                  :limit="1"
                  accept="image/jpeg,image/png"
                  tip="请上传应用icon图，比例1:1，大小不超过1M"
                  dialog-title="请裁剪您的图片"
                  :auto-crop-width="120"
                  :auto-crop-height="120"
                  :fixed="true"
                  :center-box="true"
                  :fixed-number="[1, 1]"
                  :fixed-box="false"
                  @crop-success="handleIconImages"
                />
              </el-form-item>
              <el-form-item label="APP标签" class="app-label-item">
                <template v-for="(itm, idx) in appLabelList" :key="idx">
                  <div class="app-label-input">
                    <el-input l-input v-model="itm.appLabelValue" show-word-limit maxlength="4" placeholder="请输入APP标签"> </el-input>
                    <el-icon v-if="idx != 0" style="margin-left: 10px; cursor: pointer" @click="appLabelList.splice(appLabelList.indexOf(itm), 1)"
                      ><Close
                    /></el-icon>
                  </div>
                </template>
                <p class="add-label" @click="addAppLabel" v-if="appLabelList.length < 3">+ 添加</p>
              </el-form-item>
              <el-form-item label="引导文案">
                <el-input v-model="form.anchorInfo.netServiceAnchor.guideText" show-word-limit maxlength="15" placeholder="请输入引导文案">
                </el-input>
              </el-form-item>
              <el-form-item label="APP图片" class="app-img">
                <span style="color: #999; font-size: 12px; display: block">请选择图片展示比例</span>
                <div>
                  <el-radio-group v-model="form.anchorInfo.netServiceAnchor.anchorImageMode" @change="handleImageRadio">
                    <el-radio-button label="横向(2:1)" value="100" />
                    <el-radio-button label="竖向(3:5)" value="200" />
                  </el-radio-group>
                  <div>
                    <span style="color: #999; font-size: 11px; display: block"
                      >请上传最少3张，最多8张大小不超过5M的图片，支持裁剪，推荐尺寸120*200px</span
                    >
                    <!-- <NewImageUpload
                      v-model="appImages"
                      :accountId="appStore.accountId"
                      :advertiserId="form.advertiserId"
                      limit="8"
                      :enableCrop="true"
                    /> -->
                    <CropperImageUpload
                      v-model="form.imageUrl"
                      :accountId="appStore.accountId"
                      :advertiserId="form.advertiserId"
                      :limit="8"
                      accept="image/jpeg,image/png"
                      tip="请上传JPEG或PNG图片，大小不超过5MB"
                      dialog-title="请裁剪您的图片"
                      :auto-crop-width="cropWidth"
                      :auto-crop-height="cropHeight"
                      :fixed-number="form.anchorInfo.netServiceAnchor.anchorImageMode == '100' ? [2, 1] : [3, 5]"
                      :fixed-box="true"
                      :center-box="false"
                      :fixed="true"
                      @crop-success="handleCropSuccess"
                    />
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="APP详情">
                <el-input
                  v-model="form.anchorInfo.netServiceAnchor.appDescription"
                  show-word-limit
                  maxlength="200"
                  placeholder="请详细介绍APP内容与亮点"
                  type="textarea"
                  :rows="4"
                />
              </el-form-item>
              <el-form-item label="小说章节">
                <el-input
                  v-model="form.anchorInfo.netServiceAnchor.novelChapter"
                  show-word-limit
                  maxlength="9999"
                  placeholder="非必填，请填写小说章节预览"
                  type="textarea"
                  :rows="4"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="preview">888</div>
    </div>
    <div class="footer">
      <el-button type="primary" @click="submitForm">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from '@/store/modules/app';
import { addCreateNativeAnchor } from '@/api/advertisement/nativeAnchor';
import { wechatMircroAppList } from '@/api/com';

const appStore = useAppStore();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['drawerVisible', 'advertiserId']);
const emit = defineEmits(['update:drawerVisible', 'update:drawerTitle']);
const route = useRoute();
const radio1 = ref('1');
const checkedCities = ref(['安卓', 'iOS']);
const cities = ['安卓', 'iOS'];
const boNetServiceType = ref('2');
const smNetServiceType = ref(['MICRO_APP']);
const smNetServiceTypeValueList = ref(['MICRO_APP']);
const newAdvertiserId = ref();

const cropWidth = ref(280);
const cropHeight = ref(140);

const smNetServiceTypeList = ref([
  // 'WECHAT_PACKAGE', 'MICRO_APP','WECOM_PACKAGE','WECHAT_EXTERNAL_URL'
  // {
  //   label: '添加微信号',
  //   value: 'WECHAT_PACKAGE'
  // },
  {
    label: '进入微信小程序',
    value: 'MICRO_APP'
  }
  // {
  //   label: '企业微信客服',
  //   value: 'WECOM_PACKAGE'
  // },
  // {
  //   label: '跳转微信链接',
  //   value: 'WECHAT_EXTERNAL_URL'
  // }
]);
const appLabelList = ref([
  {
    appLabelValue: '精彩剧情'
  }
]);

const appList = ref([]);

// const form = reactive({
//   name: '',
//   accountId: appStore.accountId,
//   advertiserId: 1826828145990666
// });
const headImageList = ref([]);
const iconImages = ref([]);
const appImages = ref([]);
// 基础设置
const initFormData: formData = {
  accountId: appStore.accountId,
  advertiserId: '',
  anchorInfo: {
    anchorType: 'APP_INTERNET_SERVICE',
    toolTitle: '',
    netServiceAnchor: {
      anchorImageMode: '100',
      androidAnchorTitle: '精彩剧情，热播中',
      iosAnchorTitle: '精彩剧情，热播中',
      netServiceType: '',
      appTags: [''],
      guideText: '精彩剧情，热播中',
      appDescription: '想看的内容找不到资源怎么办？打造您的专属剧场！关注我，海量精品短剧，想看就看！'
    }
  }
};
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accountId: appStore.accountId,
    advertiserId: 1826828145990666,
    anchorId: undefined,
    anchorName: undefined,
    status: undefined,
    params: {}
  },
  rules: {}
});
const { queryParams, form, rules } = toRefs(data);
const addAppLabel = () => {
  appLabelList.value.push({
    appLabelValue: ''
  });
};

const handelInstanceId = () => {
  form.value.anchorInfo.netServiceAnchor.pathParam = appList.value.find(
    (item) => item.instanceId === form.value.anchorInfo.netServiceAnchor.instanceId
  )?.path;
};

/**
 * 图片裁剪比例
 */
const handleImageRadio = () => {
  if (form.value.anchorInfo.netServiceAnchor.anchorImageMode == '100') {
    cropWidth.value = 280;
    cropHeight.value = 140;
  } else {
    cropWidth.value = 140;
    cropHeight.value = 230;
  }
};
watch(
  () => props.drawerVisible,
  (val) => {
    form.value.advertiserId = props.advertiserId;
    newAdvertiserId.value = props.advertiserId;
    queryParams.value.advertiserId = props.advertiserId;
  },
  { immediate: true }
);
watch(
  () => props.advertiserId,
  (val) => {
    console.log(val, 'val');
    form.value.advertiserId = val;
    newAdvertiserId.value = val;
    queryParams.value.advertiserId = val;
  },
  { immediate: true }
);
onActivated(() => {});
onMounted(() => {
  console.log(props.advertiserId, 'props.advertiserId');
  if (props.drawerVisible) {
    window.scrollTo(0, 0);
  }
  form.value.advertiserId = props.advertiserId;
  newAdvertiserId.value = props.advertiserId;
  queryParams.value.advertiserId = props.advertiserId;
});
const handleImageList = (val) => {
  headImageList.value = val.map((item) => {
    return {
      uri: item.url,
      width: item.width,
      height: item.height
    };
  });
};
const handleIconImages = (val) => {
  iconImages.value = val.map((item) => {
    return {
      uri: item.url,
      width: item.width,
      height: item.height
    };
  });
  console.log('iconImages.value', iconImages.value);
};
// 裁剪
const handleCropSuccess = (val) => {
  console.log('裁剪后的文件:', val);
  appImages.value = val.map((item) => {
    return {
      uri: item.url,
      width: item.width,
      height: item.height
    };
  });
  // uploadToServer(file)
};
const handleRadioNetServiceType = (val: string) => {
  // form.value.anchorInfo.netServiceAnchor.netServiceType = val;
  // if (val == '2') {
  // form.value.anchorInfo.netServiceAnchor.netServiceType = 'MICRO_APP';
  // }
};
const handleRadioAnchorType = (val: string) => {
  form.value.anchorInfo.anchorType = val;
};
const submitForm = () => {
  if (appImages.value.length < 3) {
    ElMessage.error('请上传至少3张APP图片');
    return;
  }
  form.value.anchorInfo.netServiceAnchor.appTags = appLabelList.value.map((item) => item.appLabelValue);
  form.value.anchorInfo.netServiceAnchor.headImageList = headImageList.value;
  form.value.anchorInfo.netServiceAnchor.netServiceType = 'MICRO_APP';
  form.value.anchorInfo.netServiceAnchor.iconImages = iconImages.value;
  form.value.anchorInfo.netServiceAnchor.appImages = appImages.value;
  // form.value.anchorInfo.netServiceAnchor.instanceId = '57'; //测试用
  console.log(headImageList.value, 'headImageList.value');
  // form.value.anchorInfo.netServiceAnchor.appTags = appLabelList.value.map((item) => item.appLabelValue);
  // form.anchorInfo.netServiceAnchor.headImageList = headImageList.value;
  addCreateNativeAnchor(form.value).then((res) => {
    emit('update:drawerVisible', false);
    // 清空填写的所有值
    Object.assign(form.value, initFormData);
    headImageList.value = [];
    iconImages.value = [];
    appImages.value = [];
    appLabelList.value = [
      {
        appLabelValue: ''
      }
    ];
    ElMessage.success('添加成功');
  });
};
// 清空所有数据
const cancel = () => {
  form.value = { ...initFormData };
  headImageList.value = [];
  iconImages.value = [];
  appImages.value = [];
  appLabelList.value = [
    {
      appLabelValue: ''
    }
  ];
  emit('update:drawerVisible', false);
};

const init = async () => {
  const res = await wechatMircroAppList({ pageNum: 1, pageSize: 100, accountId: appStore.accountId, advertiserId: props.advertiserId });
  appList.value = res.rows;
};

onMounted(() => {
  init();
});
</script>

<style scoped lang="scss">
.preview {
  width: 40%;
  height: 600px;
  background-color: #f0f2f5;
  border-radius: 30px;
  padding: 16px 30px;
  box-sizing: border-box;
  float: right;
}
.basic-settings,
.inlet-settings,
.page-settings {
  /* margin-top: 10px; */
  padding: 30px 0;
  box-sizing: border-box;
}

.add-native-anchor {
  width: 100%;
  height: 100%;
  .footer {
    position: fixed;
    bottom: 20px;
    right: 60px;
    width: 100%;
    padding: 10px 20px;
    box-sizing: border-box;
    text-align: right;
  }
}
.basic-settings,
.inlet-settings,
.page-settings {
  width: 100%;
}
.page-settings {
  .basic-settings-form {
    .app-label-item {
      .app-label-input {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .el-input {
          margin: 5px 0;
        }
      }
      .add-label {
        color: #409eff;
        font-size: 14px;
        cursor: pointer;
      }
    }
  }
  .app-img {
    :deep(.el-form-item__content) {
      display: block;
    }
  }
}
.basic-settings-form {
  width: 100%;
  height: 100%;
  margin-top: 10px;
  background-color: #f0f2f5;
  padding: 20px;
  box-sizing: border-box;
  border-radius: 6px;
}
.native-anchor-content {
  width: 100%;
  height: 100%;
  background-color: #fff;
}
.native-anchor-item {
  // padding-top: 20vh;
  float: left;
  width: 58%;
  height: 80vh;
  overflow-y: scroll;
  // display: flex;
  // flex-direction: column;
  // justify-content: center;
  // align-items: center;
}
.promotion {
  width: 100%;
  display: flex;
  flex-direction: column;
}
.title {
  font-size: 16px;
  font-weight: bold;
  margin: 10px 0 6px 0;
}
</style>
